package utils

import (
	"fmt"
	"github.com/playwright-community/playwright-go"
	"log"
	"time"
)

var browerContext playwright.BrowserContext

func InjectPage(page playwright.Page, scriptContent string) {

	handle, err := page.Evaluate(scriptContent, struct{}{})
	if err != nil {
		log.Fatalf("脚本执行失败: %v\n", err)
	}
	fmt.Println("脚本执行结果")
	fmt.Println(handle)

}

// https://ejia.tbea.com
func OpenPage(browser playwright.Browser, webUrlAddress string) playwright.Page {
	options := playwright.BrowserNewContextOptions{}
	var flag bool = true
	options.IgnoreHttpsErrors = &flag
	if browerContext == nil {
		browerContext, _ = browser.NewContext(options)
	}
	page, err := browerContext.NewPage()
	if err != nil {
		log.Fatalf("打开新的标签页失败: %v", err)
	}
	if _, err = page.Goto(webUrlAddress, playwright.PageGotoOptions{
		WaitUntil: playwright.WaitUntilStateDomcontentloaded,
	}); err != nil {
		log.Fatalf("加载地址失败: %v", err)
	}
	return page

}

func PostReq(page playwright.Page, url string) playwright.APIResponse {

	options := playwright.APIRequestContextPostOptions{
		Data:             nil,
		FailOnStatusCode: nil,
		Form: map[string]interface{}{
			"groupId": "XT-621d2a1bc2dc21395abfdaba-XT-2bb8a866-d2a3-47da-bbad-8c63db21e9b6",
			"userId":  "",
			"type":    "new",
			"count":   "10",
			"msgId":   "",
		},
		Headers:           nil,
		IgnoreHttpsErrors: func() *bool { b := false; return &b }(),
		MaxRedirects:      nil,
		MaxRetries:        nil,
		Multipart:         nil,
		Params:            nil,
		Timeout:           nil,
	}

	resp, err := page.Request().Post(url, options)
	if err != nil {
		log.Fatalf("创建失败context: %v", err)
		return nil
	}

	return resp
}
func WaitForUrlMatch(page playwright.Page, url string) {
	for {
		handle, err := page.Evaluate("window.location.href", struct{}{})
		if err != nil {
			log.Fatal("获取当前页面地址失败: %v", err)
		}
		//fmt.Println(handle)
		if handle == url {
			break
		}
		time.Sleep(200 * time.Millisecond)
	}
}

// 启动浏览器
func StartBrowser() playwright.Browser {
	pw, err := playwright.Run()

	if err != nil {
		log.Fatalf("自动化库加载失败: %v", err)
	}

	options := playwright.BrowserTypeLaunchOptions{

		Headless: playwright.Bool(false),
	}
	/*
		var nullStr = ""

		options.Proxy = &playwright.Proxy{
			Server:   "127.0.0.1:8899",
			Bypass:   &nullStr,
			Username: &nullStr,
			Password: &nullStr,
		}
	*/
	browser, err := pw.Chromium.Launch(options)
	if err != nil {
		log.Fatalf("谷歌浏览器启动失败: %v", err)
	}
	return browser

}
